<?php


namespace App\Cron\Command;


use EasySwoole\Component\Timer;
use EasySwoole\EasySwoole\Command\CommandInterface;
use EasySwoole\EasySwoole\Config;
use Swoole\Client;

class TcpClient implements CommandInterface
{

    public function commandName(): string
    {
        return 'tcp';
    }

    public function exec(array $args): ?string
    {
        go(function () {
            $client = new Client(SWOOLE_SOCK_TCP);
            $config = Config::getInstance()->getConf('TCP_DATA');
            if ($config['open_length_check']) {
                //是否验证数据包  true 验证 false 不验证
                $client->set($config['set_data']);
            } else {
                $client->set(['open_length_check' => false]);
            }

            if (!$client->connect('127.0.0.1', 9502, 10)) {
                echo '链接失败  错误状态码：', $client->errCode;
                return false;
            }

            Timer::getInstance()->loop(5000, function () use ($client) {
                $str = '{"class":"TcpMessage","action":"run","content":{"name":"刘强"}}';
                $client->send($this->encode($str));
                $data = $client->recv();
                if ($data) {
                    echo $this->decode($data), PHP_EOL;
                }
            });
//            while (true) {
//
//            }


        });

        return true;
    }

    public function help(array $args): ?string
    {

    }

    /**
     * @param $str
     * @return string
     * 数据包 pack处理
     */
    private function encode($str)
    {
        return pack('N', strlen($str)) . $str;
    }


    private function decode($str)
    {
        $data = substr($str, '4');
        return $data;
    }

}
